# -*- coding: utf-8 -*-
__author__ = 'Paul'
import random
from zope import schema
from zope.formlib import form
from zope.interface import implements
from zope.component import getMultiAdapter
from plone.app.portlets.portlets import base
from plone.memoize.instance import memoize
from plone.portlets.interfaces import IPortletDataProvider
from DateTime import DateTime
from Products.Five.browser.pagetemplatefile import\
    ViewPageTemplateFile
from Products.CMFCore.utils import getToolByName
from Products.bpContents import _
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm

from plone.memoize.compress import xhtml_compress
from Products.bpContents.articulo import IArticulo
from Products.bpContents.galeria import IGaleria
from Products.bpContents.evento import IEvento
from zope.schema.interfaces import IVocabularyFactory

from zope.site.hooks import getSite
import unicodedata
from intereses_portlets import CanalesVocabularyFactory
from Acquisition import aq_parent,aq_base,aq_inner

from OFS.interfaces import IOrderedContainer
from Products.ATContentTypes.interfaces.image import IATImage

CanalesVocabularyFactory

class IInteresesDPortlet(IPortletDataProvider):
    count = schema.Int(title=_(u'Number of items to display'),
        description=_(u'How many items to list.'),
        required=True,
        default=3)

    canal = schema.Choice(
        title=_(u"Canal"),
        vocabulary='bp.CanalesVocab',
    )
    categoria = schema.Choice(
        title=_(u"Categoria"),
        vocabulary='bp.CanalesVocab',
        )

class Assignment(base.Assignment):
    implements(IInteresesDPortlet)

    def __init__(self, count=5,canal=[], categoria=[]):
        self.count = count
        self.canal = canal
        self.categoria=categoria

    @property
    def title(self):
        cadena=""
        try:
            cadena="Intereses Destacado: "+self.data.canal.split("/")[-1]
        except :
            cadena="Intereses Destacado"
        return cadena


class Renderer(base.Renderer):
    ##_template = ViewPageTemplateFile('intereses_portlet.pt')
    render = ViewPageTemplateFile('intereses_d_portlet.pt')

    def __init__(self, *args):
        base.Renderer.__init__(self, *args)
        self.idDestacado=""
        self.idCanal=""
        self.canalUrl=""
        context = aq_inner(self.context)
        portal_state = getMultiAdapter((context, self.request), name=u'plone_portal_state')
        self.anonymous = portal_state.anonymous()
        self.portal_url = portal_state.portal_url()
        self.typesToShow = portal_state.friendly_types()

        plone_tools = getMultiAdapter((context, self.request), name=u'plone_tools')
        self.catalog = plone_tools.catalog()
        self.portal = getMultiAdapter((self.context, self.request),
            name=u'plone_portal_state').portal()

    @property
    def available(self):
        items=self._data()
        return items is not None

    def recent_items(self):
        return self._data()

    def recently_modified_link(self):
        return '%s/recently_modified' % self.portal_url

    def getDestacado(self):
        ##recreaFolder= self.getContainer(folder.encode('utf8'))
        ##cuando busca documento hace referencia al campo "documento" que es el destacado del directorio
        cutString=170
        art=self.hasDestacado()
        if art:
            if len(art.Description())>cutString:
                subStrRes=art.Description()[:cutString][0:art.Description()[:cutString].rfind(" ")]+" ..."
            else:
                subStrRes=art.Description()
                #subDescri=art.Description()[0:maxFiledSize]

            articulo={
                "id":art.id,
                "categoria":aq_inner(aq_parent(art)).Title(),
                "cateURL":aq_inner(aq_parent(art)).absolute_url(),
                "titulo":art.Title,
                "tipo":art.portal_type,
                "resumen":subStrRes,
                "url":art.absolute_url()
            }

            if art.portal_type == "Products.bpContents.libro" :
                if art.portada==None:
                    articulo["imagen"]=False
                else:
                    articulo["imagen"]=art
                """articulo["categoria"]=aq_inner(aq_parent(art)).title
                articulo["cateURL"]=aq_inner(aq_parent(art)).absolute_url()"""
            else:
                articulo["imagen"]=self.getIMG(art.getPhysicalPath())
            return articulo
        else:
            result=self.damePrimeroDelMonton()
            if result:
                return result
            else:
                return None

    def hasDestacado(self):
        """Averigua si el directorio tiene un elemento destacado"""
        canalFolder = aq_base(self.portal["home"]["intereses"][self.idCanal])
        if hasattr(canalFolder,"documento"):
            if canalFolder.documento==None:
                return None
                
            artticulo=None
            if len(canalFolder.documento)>0:
               artticulo=canalFolder.documento[0].to_object
 
            if artticulo!=None:
                self.idDestacado=artticulo.id
                return artticulo
            else:
                return None

    def damePrimeroDelMonton(self):
        """Devuelve un objeto del primer documento de la sección"""
        if len(self.getArticulosTMP())>0:
            art=self.getArticulosTMP()[0]
            self.idDestacado=art["id"]
            return art
        else:
            return None

    def getMasArticulos(self):
        return self.getArticulosTMP()

    def getArticulos(self):
        if self.hasDestacado():
            return self.getArticulosTMP()
        else:
            return self.getArticulosTMP()[1:]


    def getArticulosTMP(self):
        resultado = []
        flag=0
        cutString=100
        dameUnoMas=False

        for art in self._data():
            rutaLista=self.data.canal.split("/")
            rutaPadre=self.portal.absolute_url()+"/"+"/".join(rutaLista[rutaLista.index("home"):-1])
            if rutaLista[-1]=="recreacion":
                subst=art.getPath()
                subst1=subst[0:subst.rindex("/")]
                subst2=subst1[subst1.rindex("/")+1:]
                cate=self.portal.unrestrictedTraverse(subst1).title
            else:
                cate=False

            if flag== self.data.count and not dameUnoMas:
                break
            else:
                if art.id != self.idDestacado:
                    if len(art.Description)>cutString:
                        subStrRes=art.Description[:cutString][0:art.Description[:cutString].rfind(" ")]+" ..."
                    else:
                        subStrRes=art.Description

                    articulo={
                        "id":art.id,
                        "categoria":cate,
                        "cateURL":rutaPadre,
                        "titulo":art.Title,
                        "resumen":subStrRes,
                        "tipo":art.portal_type,
                        "url":art.getURL(),
                    }


                    if art.portal_type=="Products.bpContents.libro":
                        try:
                            if art.portada==None:
                                articulo["imagen"]=False
                            else:
                                articulo["imagen"]=art
                        except AttributeError:
                            articulo["imagen"]=False
                    else:
                        articulo["imagen"]=self.getIMG(art.getPath())


                    resultado.append(articulo)
                else:
                    dameUnoMas=True
            flag=flag+1
        return resultado

    def getCanal(self):
        folderId=self.idCanal
        try:
            if folderId=="apoyo_educacion" or folderId=="apoyo-a-la-educacion":
                folderId="Apoyo a la Educación"
            elif folderId=="recreacion":
                folderId="Recreación"
            elif folderId=="investigacion":
                folderId="Investigación"
            else:
                folderId=folderId[0].upper()+folderId[1:]
        except :
            folderId=folderId[0].upper()+folderId[1:]

        pp=( folderId,self.canalUrl)
        return pp

    def getIMG(self,ruta):

        if not isinstance(ruta,basestring):
            ruta="/".join(ruta)
            padreObj=self.portal.unrestrictedTraverse(ruta)

        padreObj=self.portal.unrestrictedTraverse(ruta)

        if padreObj.portal_type=="Products.bpContents.libro":
            return None
        else:
            baseQ={'object_provides' : (IATImage.__identifier__,),
            'allowedRolesAndUsers' : ('Anonymous',),
            'path': {'query': ruta, 'depth': 1}
            }

            search=self.catalog(baseQ,sort_on='modified',sort_order='reverse')

            if len(search)>0:
                img=padreObj[search[0].id]
                return img
            else:
                return None


    def _data(self):
        limit = self.data.count+1
        folder = self.data.canal
        self.idCanal=folder.split("/")[-1]
        folderObj=self.catalog(id=self.idCanal)


        if len(folderObj)>0:
            self.canalUrl=folderObj[0].getURL()

        #self.canalUrl=folder.absolute_url()

        result=self.catalog(
            path=folder,
            sort_on='modified',
            object_provides=("Products.bpContents.articulo.IArticulo",
                             "Products.bpContents.libro.ILibro",
                             "Products.bpContents.galeria.IGaleria",
                            "Products.bpContents.evento.IEvento",),
            sort_order='reverse')[:limit]
        return result

    @memoize
    def getContainer(self, path):
        if not path:
            return None
        if path.startswith('/'):
            path = path[1:]
        if not path:
            return None

        return aq_inner(self.portal).restrictedTraverse(path, default=None)

    def get_position_in_parent(self,objId):
        """ Use IOrderedContainer interface to extract the object's manual ordering position
        """
        obj=self.catalog(id=objId)[0]
        parent = obj.aq_inner.aq_parent
        ordered = IOrderedContainer(parent, None)

        if ordered is not None:
            return ordered.getObjectPosition(objId)
        return 0



class AddForm(base.AddForm):
    form_fields = form.Fields(IInteresesDPortlet)
    label = _(u"Add Recent Portlet")
    description = _(u"This portlet displays recently modified content.")

    def create(self, data):
        return Assignment(count=data.get('count', 3),canal=data.get('canal',[]))

class EditForm(base.EditForm):
    form_fields = form.Fields(IInteresesDPortlet)
    label = _(u"Edit Recent Portlet")
    description = _(u"This portlet displays recently modified content.")